package cn.alm.allinoneboot.controller;

import cn.alm.allinoneboot.common.CommonResult;
import cn.alm.allinoneboot.dto.CommonDto;
import cn.alm.allinoneboot.service.ApiService;
import cn.alm.allinoneboot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("api/user")
@CrossOrigin(origins = "*", maxAge = 3600)
@Slf4j
public class UserController {

    @Resource
    UserService userService;

    @Resource
    ApiService apiService;

    @PostMapping("info")
    public CommonResult info(@RequestHeader(value = "authorization", required = false) String authorization, @RequestBody CommonDto dto) {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return userService.info(dto.getUsername());
    }

    @PostMapping("login")
    public CommonResult login(@RequestBody CommonDto dto) throws Exception {
        return userService.login(dto);
    }

    @PostMapping("createUser")
    public CommonResult createUser(@RequestHeader(value = "authorization", required = false) String authorization,@RequestBody CommonDto dto) throws Exception {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return userService.createUser(dto);
    }

    @PostMapping("logout")
    public CommonResult logout(@RequestHeader(value = "authorization", required = false) String authorization,@RequestBody CommonDto dto) {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return userService.logout(dto);
    }

}
